'use strict'

module.exports = (options, app) => {
	return async function jwtAuth(ctx, next) {
		// 检查白名单
		const ignorePaths = options.ignore 
		if (ignorePaths.some(path => ctx.path.startsWith(path))) {
			return next()
		}

		// 获取token
		const token = ctx.request.header.authorization?.split(' ')[1]
        console.log('middleware jwt token', token)
		if (!token) {
			ctx.body = {
				code: 402,
				msg: '认证失败'
			}
		}

		try {
            
			// 验证token
			const decoded = app.jwt.verify(token, app.config.jwt.secret)
            console.log('jwt decoded', decoded)  
			ctx.state.user = decoded
			await next()
		} catch (err) {
			console.log('jwt error', err)
			ctx.body = {
				code: 401,
				msg: '认证失败'+err
			}
		}
	}
}
